<template>
	<el-container>
		<el-header class="header-tabs">
			<el-tabs type="card" v-model="groupId" @tab-change="tabChange">
				<el-tab-pane label="待创建合同" name="0"></el-tab-pane>
				<el-tab-pane label="二次工艺合同明细" name="1"></el-tab-pane>
			</el-tabs>
		</el-header>
		<el-header v-if="groupId == 0">
			<div class="right-panel-search">
                <el-input v-model="search.order_no" placeholder="订单号" clearable @change="handleKeyDown"/>
				<el-input v-model="search.keyword" placeholder="工厂货号/批次号" clearable @change="handleKeyDown"/>
				<el-date-picker v-model="search.time_range" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :size="size"/>
				<el-button type="primary" icon="el-icon-search" @click="waitUpsearch">搜索</el-button>
			</div>
		</el-header>
		<el-main class="nopadding" v-if="groupId == 0">
			<scTable ref="table" :apiObj="apiObj" @selection-change="selectionChange" stripe remoteSort remoteFilter border :params="query" show-summary>
				<el-table-column type="selection" width="50"></el-table-column>
				<el-table-column fixed label="订单号" align="center" width="160">
					<template #default="{row}">
						<div>{{ row.order_no }}</div>
						<div>{{ row.create_time }}</div>
					</template>
				</el-table-column>
				<el-table-column label="商品信息" fixed align="center" width="300">
					<template #default="{row}">
						<div class="shopInfo" v-if="row.goods">
							<el-image class="img" :src="row.goods.goods_image" :preview-src-list="row.goods.goods_image_item" :initial-index="0" fit="cover" preview-teleported="true" hide-on-click-modal/>
							<div class="right">
								<div>工厂货号：{{ row.factory_number }}</div>
								<div>批次号：{{ row.batch_number }}</div>
								<div>SKC：{{ row.skc }}</div>
								<div>商品品牌：{{ row.brand_name }}</div>
								<div>客户：{{ row.custom_name }}</div>
								<div>颜色：{{ row.goods.colour }}</div>
								<div v-if="row.sizeCate">商品类别：{{ row.sizeCate.title }}</div>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="尺码" align="center">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.goods_size }}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="下单数量" prop="total_count" align="center">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.num }}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="计划生产数" prop="produce_count" align="center">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.produce_num }}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="待发数量" prop="pending_total" align="center">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.pending_num }}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="已发数量" prop="weaving_count" align="center">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.weaving_num }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="订单标签" align="center" width="100">
					<template #default="scope">
						<el-tag v-if="scope.row.order_label==1" type="danger">加急</el-tag>
						<el-tag v-else type="success">正常</el-tag>
					</template>
				</el-table-column>
                <el-table-column label="工序" prop="two_process_title" align="center"></el-table-column>
				<!-- <el-table-column label="针种" prop="needle_seed_name" align="center"></el-table-column>
				<el-table-column label="毛种" prop="wool_seed" align="center"></el-table-column> -->
                <el-table-column label="生产交期" prop="deliver_time" align="center" width="100" sortable></el-table-column>
				<el-table-column label="下单人" align="center" column-key="filterCreate" :filters="createFilters">
                    <template #default="{row}">
                        {{ row.creator_name }}
					</template>
                </el-table-column>
				<el-table-column label="制单人" align="center" column-key="filterMain" :filters="zhiFilters">
                    <template #default="{row}">
                        {{ row.maintenance_name }}
					</template>
                </el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="120">
					<template #default="scope">
						<el-button-group style="display:flex;flex-direction:column">
							<el-button text type="primary" size="small" @click="showContract(scope.row, scope.$index)" v-auth="'secondcontract.show'">查看委外合同单</el-button>
							<el-button text type="primary" size="small" @click="goContract(scope.row, scope.$index)" v-auth="'secondcontract.contract'">新建委外合同单</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
		<el-header v-if="groupId == 1">
			<div class="right-panel-search">
				<!-- <el-button type="primary" @click="scan" v-auth="'secondcontract.scanSend'">二次工艺扫码收货</el-button> -->
				<el-button type="primary" @click="send" v-auth="'secondcontract.send'">二次工艺收货录入</el-button>
				<!-- <el-button type="primary" @click="goRepair" :disabled="selection.length==0" v-auth="'secondcontract.reqair'">补打条码</el-button> -->
				<el-input v-model="search.contract_no" placeholder="请输入合同单号" clearable @change="handleKeyDowns"/>
				<el-input v-model="search.order_no" placeholder="请输入订单号" clearable @change="handleKeyDowns"/>
				<el-input v-model="search.keyword" placeholder="请输入工厂货号/SKC" clearable @change="handleKeyDowns"/>
				<el-button type="primary" icon="el-icon-search" @click="conUpsearch">搜索</el-button>
				<el-button type="primary" @click="allCompleted" v-auth="'secondcontract.completedAll'" :disabled="selection.length==0">批量完工</el-button>
			</div>
		</el-header>
		<el-main class="nopadding" v-if="groupId == 1">
			<scTable ref="table" :apiObj="fazhi" @selection-change="selectionChanges" stripe remoteSort remoteFilter border :params="query2"  show-summary >
				<el-table-column type="selection" width="50"></el-table-column>
				<el-table-column fixed label="合同号" align="center" width="160" sortable>
					<template #default="{row}">
						<div>{{ row.contract_no }}</div>
						<div>{{ row.create_time }}</div>
						<div>{{ row.order_no }}</div>
					</template>
				</el-table-column>
				<el-table-column label="商品信息" fixed align="center" width="300">
					<template #default="{row}">
						<div class="shopInfo" v-if="row.goods">
							<el-image class="img" :src="row.goods.goods_image" :preview-src-list="row.goods.goods_image_item" :initial-index="0" fit="cover" preview-teleported="true" hide-on-click-modal/>
							<div class="right">
								<div>工厂货号：{{ row.factory_number }}</div>
								<div>批次号：{{ row.batch_number }}</div>
								<div>SKC：{{ row.skc }}</div>
								<div>商品品牌：{{ row.brand_name }}</div>
								<div>客户：{{ row.custom_name }}</div>
								<div>颜色：{{ row.goods.colour }}</div>
								<div v-if="row.sizeCate">商品类别：{{ row.sizeCate.title }}</div>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="尺码" align="center">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.goods_size }}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="此单发织数量" prop="total_weaving_count" align="center" width="100">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.weaving_num }}
						</div>
					</template>
				</el-table-column>
				<el-table-column fixed label="已收数量" prop="total_complete_count" align="center" width="100">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.complete_num }}
						</div>
					</template>
				</el-table-column>
                <el-table-column fixed label="未收数量" prop="total_can_take_count" align="center" width="100">
					<template #default="{row}">
						<div v-for="(item,index) in row.orderDetail" :key="index">
							{{ item.can_take_num }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="订单标签" align="center" width="100">
					<template #default="scope">
						<el-tag v-if="scope.row.order_label==1" type="danger">加急</el-tag>
						<el-tag v-else type="success">正常</el-tag>
					</template>
				</el-table-column>
				<!-- <el-table-column label="针种" prop="needle_seed_title" align="center" width="100"></el-table-column>
				<el-table-column label="毛种" prop="wool_seed" align="center" width="100"></el-table-column> -->
				<el-table-column label="发织日期" prop="contract_date" align="center" width="150" sortable></el-table-column>
				<el-table-column label="生产交期" prop="due_date" align="center" width="150" sortable>
                    <template #default="scope">
                        <div v-if="scope.row.take_delivery_date>scope.row.due_date" style="color:#67c23a">{{scope.row.due_date}}</div>
                    </template>
                </el-table-column>
                <el-table-column label="最后收期" prop="take_delivery_date" align="center" width="120" sortable column-key="filterExceed" :filters="[{ text: '已超期', value: '1' }, { text: '未超期', value: '0' }]">
                    <template #default="{row}">
                            <div :style="row.take_delivery_date>row.due_date?'color:red':''">{{row.take_delivery_date}}</div>
                        </template>
                </el-table-column>
				<el-table-column label="工序" prop="produce_process_name" align="center" width="100" column-key="filterProcess" :filters="processFilters"></el-table-column>
				<el-table-column label="承制人" align="center" width="100" sortable  column-key="filterApply" :filters="chengFilters">
					<template #default="{row}">
						<div>{{row.apply_name}}</div>
					</template>
				</el-table-column>
				<el-table-column label="制单人" align="center" width="100" sortable  column-key="filterCreate" :filters="zhiFilters">
                    <template #default="{row}">
						<div>{{row.creator_name}}</div>
					</template>
                </el-table-column>
				<el-table-column label="单价" prop="price" align="center" width="100" sortable></el-table-column>
				<el-table-column label="单位" prop="unit_name" align="center" width="100"></el-table-column>
				<el-table-column label="完工" align="center" width="100" column-key="is_completed" :filters="[{ text: '是', value: '1' }, { text: '否', value: '0' }]">
					<template #default="{row}">
						<el-tag v-if="row.is_completed==1" type="success">是</el-tag>
						<el-tag v-else type="danger">否</el-tag>
					</template>
				</el-table-column>
                <el-table-column label="完工日期" align="center" width="100" sortable>
                    <template #default="{row}">
						<div>{{row.completed_date}}</div>
					</template>
                </el-table-column>
                <el-table-column label="结算月份" align="center" width="100" sortable>
                    <template #default="{row}">
						<div>{{row.settlement_date}}</div>
					</template>
                </el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="120">
					<template #default="scope">
						<el-button-group style="display:flex;flex-direction:column">
							<div v-if="contract">
								<sc-status-indicator type="danger" v-if="scope.row.contract_print==0"></sc-status-indicator>
								<el-button text type="primary" size="small" @click="contPrint(scope.row, scope.$index)" v-auth="'secondcontract.contract'">打印合同</el-button>
							</div>
                            <el-popconfirm title="确定作废该合同单吗?" @confirm="voidContract(scope.row)">
								<template #reference>
									<el-button text type="danger" size="small" v-auth="'secondcontract.void'">合同单作废</el-button>
								</template>
							</el-popconfirm>
                            <el-button text type="warning" size="small" @click="princeChange(scope.row, scope.$index)" v-auth="'secondcontract.checkPrice'">修改价格</el-button>
							<!-- <el-popconfirm title="确定标为完工吗？" @confirm="completed(scope.row)">
								<template #reference>
									<el-button text type="success" size="small" v-auth="'secondcontract.completed'">标为完工</el-button>
								</template>
							</el-popconfirm> -->
                            <el-popconfirm title="确定标为完工吗？" @confirm="completed(scope.row)" v-if="scope.row.is_completed==0">
								<template #reference>
									<el-button text type="success" size="small" v-auth="'secondcontract.completed'">标为完工</el-button>
								</template>
							</el-popconfirm>
                            <el-popconfirm title="确定取消完工吗？" @confirm="unCompleted(scope.row)" v-if="scope.row.is_completed==1">
								<template #reference>
									<el-button text type="info" size="small" v-auth="'secondcontract.uncompleted'">取消完工</el-button>
								</template>
							</el-popconfirm>
							<el-button text type="primary" size="small" @click="repair(scope.row, scope.$index)" v-auth="'secondcontract.repairMarte'">补料</el-button>
							<el-button text type="primary" size="small" @click="refund(scope.row, scope.$index)" v-auth="'secondcontract.retrunMater'">退料</el-button>
						</el-button-group>
					</template>
				</el-table-column>
			</scTable>
		</el-main>
		<con-save v-if="dialog.save" ref="saveDialog" @success="contractClose" @closed="dialog.save = false" draggable></con-save><!-- 新增委外合同-->
		<contract-list v-if="dialog.list" ref="listDialog" @success="handleSuccess" @closed="dialog.list = false" draggable :query="{produce_no:produce_no,process_id:7}"></contract-list><!-- 查看合同-->
		<print ref="pitDialog"></print> <!-- 打印 -->
        <send-input v-if="dialog.input" ref="inputDialog" @success="handleSuccess" @closed="dialog.input = false" draggable></send-input>
		<repair-mater v-if="dialog.mater" ref="materDialog" @success="handleSuccess" @closed="dialog.mater = false" draggable></repair-mater><!-- 补料 -->
		<return-mater v-if="dialog.retmater" ref="retmaterDialog" @success="handleSuccess" @closed="dialog.retmater = false" draggable></return-mater><!-- 退料 -->
		<contract-print v-if="dialog.print" ref="printDialog" @success="handleSuccess" @closed="dialog.print = false" draggable></contract-print><!-- 合同打印 -->
		<el-dialog v-model="dialog.printType" title="您将打印条码,请选择打印需求" width="300" :before-close="handleClose" align-center>
			<el-form-item label="是否打印公司名" prop="corporate">
				<el-switch v-model="corporate" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item label="是否打印客户名" prop="custom">
				<el-switch v-model="custom" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<el-form-item label="是否打印成分" prop="component">
				<el-switch v-model="component" :active-value="1" :inactive-value="0"></el-switch>
			</el-form-item>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialog.send = false">取消</el-button>
					<el-button type="primary" @click="printQr" :loading="isSaveing">确定</el-button>
				</div>
			</template>
		</el-dialog>
        <receipt-print v-if="dialog.prints" ref="printsDialog" @success="handleSuccess" @closed="dialog.prints = false" draggable></receipt-print><!-- 收货单打印 -->
        <price-check v-if="dialog.price" ref="priceDialog" @success="handleSuccess" @closed="dialog.price = false" draggable></price-check>修改价格
	</el-container>
</template>
<script>
import Print from '@/views/order/print.vue'
import ContractList from './contractList';
import ConSave from './conSave.vue';
import RepairMater from './repairMater.vue';
import ReturnMater from './returnMater.vue';
import ContractPrint from './contractPrint.vue';
import receiptPrint from '../../produceLoom/send/receiptPrint.vue';
import SendInput from './sendInput.vue';
import PriceCheck from '../../produceLoom/contract/priceCheck.vue';

export default {
	components: {Print, ContractList,  ConSave,  RepairMater, ReturnMater, ContractPrint,receiptPrint, SendInput, PriceCheck, },
	name: 'user',
	data() {
		return {
			dialog: {
                save: false,
				list: false,
				input: false,
				scan: false,
				repair: false,
				printType: false,
				mater: false,
				retmater: false,
				print: false,
				prints: false,
                price:false,
			},
			group: [],
			apiObj: this.$API.produce.getProduce.lists,
			fazhi: this.$API.produce.contract.viewContract,
			query: {
				planned_speed: 4,
				process_id: 7,
				plan_type: 0
			},
			query2: {
				process_id: 7,
			},
			selection: [],
			needleList: [],//针种
			search: {
				time_range: null,
				keyword: null,
				supplier_id: null,
				creator: null,
				order_no: null,
			},
			produce_no: "",
			groupId: "0",
			apply: [],
			applyList: [],
			printID: "",
			isSaveing: false,
			corporate: 0,
			custom: 0,
			component: 0,
			chengFilters: [],
			zhiFilters: [],
            createFilters:[],
            processFilters:[],
            place:1,
            contract:this.$TOOL.data.get("PERMISSIONS").includes('secondcontract.contract'),
		}
	},
	mounted() {
        this.getCreate()
    },
	methods: {
		/**批量完工*/
		async allCompleted() {
			var contract_no_arr = [];
			this.selection.map((item) => {
				contract_no_arr.push(item.contract_no)
			})
			this.$confirm(`确定完工选中的 ${this.selection.length} 项吗？`, '提示', {
				type: 'warning'
			}).then(() => {
				this.table_del_all(contract_no_arr)
			}).catch(() => {

			})
		},
		async table_del_all(contract_no_arr) {
			var reqData = {contract_no_arr: contract_no_arr}
			var res = await this.$API.produce.send.markCompleted.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		// 查看委外合同单
		showContract(row) {
			this.produce_no = row.produce_no
			this.dialog.list = true
			this.$nextTick(() => {
				this.$refs.listDialog.open('add').setData(row)
			})
		},
         // 修改价格
        princeChange(row) {
			this.dialog.price = true
			this.$nextTick(() => {
				this.$refs.priceDialog.open('edit').setData(row)
			})
		},
		// 打印合同单
		async contPrint(row) {
			var reqData = { contract_no_arr: row.contract_no };
			var res = await this.$API.print.contractPrint.get(reqData);
			if (res.code == 1) {
			    this.dialog.print = true;
			    setTimeout(()=>{
			        this.$refs.printDialog.open("show").setData(res.data);
			    },500)
                this.conUpsearch()
			} else {
				this.$alert(res.message, "提示", { type: "error" });
			}
		},
        async voidContract(row) {
			var reqData = {contract_no_arr: row.contract_no}
			var res = await this.$API.produce.void.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		// 新建委外合同单
		goContract(row) {
			this.dialog.save = true
			this.$nextTick(() => {
				this.$refs.saveDialog.open('add').setData(row)
			})
		},
		//标记完工
		async completed(row) {
			var reqData = {contract_no_arr: row.contract_no}
			var res = await this.$API.produce.send.markCompleted.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
        // 取消完工
        async unCompleted(row) {
			var reqData = {contract_no_arr: row.contract_no}
			var res = await this.$API.produce.send.unCompleted.post(reqData);
			if (res.code == 1) {
				this.$refs.table.refresh()
				this.$message.success("操作成功")
			} else {
				this.$alert(res.message, "提示", {type: 'error'})
			}
		},
		// 补毛
		repair(row) {
			this.dialog.mater = true
			this.$nextTick(() => {
				this.$refs.materDialog.open('edit').setData(row)
			})
		},
		// 退毛
		refund(row) {
			this.dialog.retmater = true
			this.$nextTick(() => {
				this.$refs.retmaterDialog.open('edit').setData(row)
			})
		},
		// 控制单选
		selectAll() {
			this.$message.error("请选择一条数据！")
			this.$refs.table.clearSelection()
		},
		// 收货录入
		send() {
            if(this.selection.length > 1){
                this.$message.error("请选择一条数据！")
                return
            }
			this.dialog.input = true;
			this.$nextTick(() => {
				this.$refs.inputDialog.open("add").setData(this.selection[0]);
			});

		},
		// 打印
		async print(row) {
			this.printID =  row.contract_no;
			this.dialog.printType = true
		},
		async printQr() {
			this.isSaveing = true;
            let data = { contract_no_arr:this.printID,has_company:this.has_company,has_custom:this.has_custom ,has_component:this.has_component};
			var res = await this.$API.print.loomBarcodePrint.get(data);
			this.isSaveing = false;
			if (res.code == 1) {
				this.$refs.pitDialog.init(res.data);
				this.dialog.printType = false
                this.has_company = 0
                this.has_custom = 0
                this.has_component = 0
                this.$refs.table.refresh()
			} else {
				this.$alert(res.message, "提示", {type: "error"});
			}
		},
		//搜索
		waitUpsearch() {
			this.$refs.table.upData(this.search)
		},
		conUpsearch() {
			this.$refs.table.upData(this.search)
		},
		//本地更新数据
		handleSuccess(data, mode) {
			if (mode == 'add') {
				this.$refs.table.refresh()
			} else if (mode == 'edit') {
				this.$refs.table.refresh()
			} else if (mode == 'set') {
				this.$refs.table.refresh()
			}
		},
		selectionChanges(selection) {
			// if (selection.length > 1) {
			// 	const del_row = selection.shift()
			// 	this.$refs.table.toggleRowSelection(del_row, false) //设置这一行取消选中
			// }
			this.selection = selection;
		},
		tabChange(e) {
			this.groupId = e
			for (const key in this.search) {
                this.search[key] = null;
            }
            this.place = Number(e )+ 1
            this.getCreate()
            if(e==1){
                this.conUpsearch()
            }else{
                this.waitUpsearch()
            }
		},
		handleKeyDown() {
			this.waitUpsearch()
		},
		handleKeyDowns() {
			this.conUpsearch()
		},
		filterHandler(value, row, column) {
			const property = column['property']
			return row[property] === value
		},
        // 下单人/制单人
        async getCreate() {
            var res = await this.$API.all.getProduceFilter.get({process_id:7
            ,place:this.place});
			let order = []
			let maintenance = []
			let apply = []
            let process = []
            res.data.maintenance_creator.map(item => {
                maintenance.push({
                    text: item.name,
                    value: item.id,
                })
            })
            if(this.place==1){
                res.data.order_creator.map(item => {
                    order.push({
                        text: item.name,
                        value: item.id,
                    })
                })
            }else if(this.place==2){
                res.data.supplier_list.map(item => {
                    apply.push({
                        text: item.name,
                        value: item.id,
                    })
                })
                res.data.process_list.map(item => {
                    process.push({
                        text: item.title,
                        value: item.id,
                    })
                })
            }
			this.createFilters = order
			this.zhiFilters = maintenance
			this.chengFilters = apply
            this.processFilters = process
		},
        printClose(data, mode,c) {
			if (mode == 'add') {
				this.$refs.table.refresh()
			} else if (mode == 'edit') {
				this.$refs.table.refresh()
			} else if (mode == 'set') {
				this.$refs.table.refresh()
			}
            if(c==undefined){
                console.log(11.02);
            }else{
                this.dialog.prints = true;
                setTimeout(()=>{
                    this.$refs.printsDialog.open("show").setData(c);
                },500)
            }
		},
        contractClose(data, mode,c) {
			if (mode == 'add') {
				this.$refs.table.refresh()
			} else if (mode == 'edit') {
				this.$refs.table.refresh()
			} else if (mode == 'set') {
				this.$refs.table.refresh()
			}
            if(c==undefined){
                console.log(11.02);
            }else{
                this.dialog.print = true;
                setTimeout(()=>{
                    this.$refs.printDialog.open("show").setData(c);
                },500)
            }
		},
	}
}
</script>

<style>
.search-input {
	width: auto;
	font-size: 14px;
}
</style>
